﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using WP.Commons;
using WP.DB;
using WP.Modules;
using WP.Controls;
using WP.Controls.GridColumn;


using WP.RM.BusinessRule;
using WP.RM.BusinessLogical;
using WP.RM.DataAccess;
using System.IO;

namespace WP.RM.Form
{
    public partial class frmRMUpdateFromK3Mtn : BaseQryRpt 
    {
        
        public frmRMUpdateFromK3Mtn()
        {
            InitializeComponent();
        }
        private string mstrFieldName = Application.StartupPath +"\\UpdateFromK3.XmL";
        private struct Connect
        {
            public string strServerName;
            public string strDBName;
            public string strUserName;
            public string strPassword;
        }
        private Connect mK3Connect = new Connect();

        private bool GetK3Connect()
        {
          
           
            return true;
        }

        private void FillConnect()
        {
            bool blnNew = false;

            string strFileName = mstrFieldName;
            string strPathName = mstrFieldName.Replace("\\UpdateFromK3.XmL", "");

            strFileName = strPathName + "\\UpdateFromK3.XmL";
            mstrFieldName = strFileName;
            if (!File.Exists(mstrFieldName))
            {
                txtUserName.Text = "Sa";
                txtPassWord.Text = "happytoo15";
                return;
            }

            DataTable dtTable = new DataTable();
            dtTable.ReadXml(strFileName);
            foreach (DataRow drRow in dtTable.Rows)
            {  
               
                string strUserName = string.Empty;
                string strPwd = string.Empty;
                string strServerName = string.Empty ;
                string strDBName = string.Empty ;

                AnalysConStr(drRow["ConnectString"].ToString(), ref  strServerName, ref strDBName , ref strUserName ,ref strPwd);
                                 
                txtServerName.Text = strServerName;
                txtDBName.Text  = strDBName;
                txtUserName.Text = strUserName;
                txtPassWord.Text = strPwd;

                mK3Connect.strPassword = strPwd;
                mK3Connect.strDBName = strDBName;
                mK3Connect.strUserName = strUserName;
                mK3Connect.strServerName = strServerName;
            }            

        }

        private void AnalysConStr(string strConStr, ref string strServerName, ref string strDBName, ref string strUserName, ref string strPwd)
        {
            //data source=Boserver1\SQL2005;database=RTBP20090902;Connect Timeout=90;uid=procom;pwd=2W00dpr00;
            string[] strServerandDB = strConStr.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
            if (strConStr != "" && strServerandDB.Length == 0)
            {

            }
            else
            {
                for (int i = 0; i < strServerandDB.Length; i++)
                {
                    strServerName = strServerandDB[i].Split(new char[] { ';' })[0];
                    strServerName = strServerName.Replace("data source=", "");
                    strDBName = strServerandDB[i].Split(new char[] { ';' })[1];
                    strDBName = strDBName.Replace("database=", "");

                    strUserName = strServerandDB[i].Split(new char[] { ';' })[3];
                    strUserName = strUserName.Replace("uid=", "");
                    strPwd = strServerandDB[i].Split(new char[] { ';' })[4];
                    strPwd = strPwd.Replace("pwd=", "");


                }
            }
        }

        private bool UpdateXML()
        {
            mK3Connect.strPassword = txtPassWord.Text  ;
            mK3Connect.strDBName = txtDBName.Text ;
            mK3Connect.strUserName = txtUserName.Text  ;
            mK3Connect.strServerName = txtServerName.Text   ;

            string strConDB = @"data source=" + mK3Connect.strServerName + ";database=" + mK3Connect.strDBName + ";Connect Timeout=90;uid=" + mK3Connect.strUserName + ";pwd=" + mK3Connect.strPassword + ";";
            DataTable dtRecalItemQty = new DataTable("ImRecalcQty");
            dtRecalItemQty.Columns.Add(new DataColumn("ConnectString", typeof(string)));
            dtRecalItemQty.Rows.Add();
            DataRow dr = dtRecalItemQty.Rows[0];
            dr["ConnectString"] = strConDB;
            dtRecalItemQty.AcceptChanges();
            if (File.Exists(mstrFieldName)) File.Delete(mstrFieldName);
            dtRecalItemQty.WriteXml(mstrFieldName, XmlWriteMode.WriteSchema, false);
            return true;
        }

        private bool UpdateFromK3()
        {
            progressBar1.Visible = true ;
            progressBar1.Value = 0;
            DBAccess dbPDMcon = new DBAccess ( false,false );

            string strOoldCon = DBAccess.mConnectionString;
            string strConDB = @"data source=" + mK3Connect.strServerName + ";database=" + mK3Connect.strDBName + ";Connect Timeout=90;uid=" + mK3Connect.strUserName + ";pwd=" + mK3Connect.strPassword + ";";
            DBAccess.ConnectionDBString = strConDB;
            DBAccess dbK3con = new DBAccess(false, false);
            DBAccess.ConnectionDBString = strOoldCon;
            string strSQL = "";
            if (chkUpdateItem.Checked)
            {
                strSQL = @"select t.fitemid as 物料内码,t.fnumber as 物料代码,t.fname as 物料名称 ,t.fparentid as 物料类别内码,
                            m.fnumber as 物料类别代码,right(m.ffullname,(len(m.ffullname)-4))as 物料类别名称,s.fname as 基本计量单位
                            from t_icitem t ,t_item m ,t_measureunit s where t.fnumber like '1.%'and  t.fparentid = m.fitemid
                            and t.funitid=s.fmeasureunitid";
                DataTable dtK3 = dbK3con.GetDataTable(strSQL);
                progressBar1.Maximum = dtK3.Rows.Count+10;
                strSQL = "select * from iminvmaster";
                DataTable dtPDM = dbPDMcon.GetDataTable(strSQL);
                DataView dvPDM = dtPDM.DefaultView;
                foreach (DataRow drK3 in dtK3.Rows)
                {
                    progressBar1.Value++;
                    dvPDM.RowFilter = "FItemID='" + drK3["物料内码"] + "'";
                    if (dvPDM.Count <= 0)  //Add Items
                    {
                        strSQL = @"Insert into ImInvMaster(FItemID,ItemNo,ItemName,MaterialType,MaterialTypeID,CostUnit)
                                   Values ('{0}','{1}','{2}','{3}','{4}','{5}') ";
                        strSQL = string.Format(strSQL , drK3["物料内码"]
                                                      , drK3["物料代码"]
                                                      , drK3["物料名称"]
                                                      , drK3["物料类别名称"]
                                                      , drK3["物料类别代码"]
                                                      , drK3["基本计量单位"]);
                    }
                    else  //Update Items
                    {
                        strSQL = @"update ImInvMaster set ItemNo='{0}',ItemName='{1}',MaterialType='{2}',MaterialTypeID='{3}',CostUnit='{4}' where FItemID='{5}'";
                        strSQL = string.Format(strSQL , drK3["物料代码"]
                                                      , drK3["物料名称"]
                                                      , drK3["物料类别名称"]
                                                      , drK3["物料类别代码"]
                                                      , drK3["基本计量单位"]
                                                      , drK3["物料内码"]
                                                      );
                    }
                    dbPDMcon.ExecuteSql(strSQL); 
                }
            }
            if (chkMaterial.Checked)
            {
                strSQL = @"select fitemid as 物料类别内码,fnumber as 物料类别代码,
                            right(ffullname,(len(ffullname)-4)) as 物料类别名称 from t_item where fitemclassid = 4 and 
                            fnumber like '1.%' and flevel=3";
                DataTable dtK3 = dbK3con.GetDataTable(strSQL);
                progressBar1.Maximum = dtK3.Rows.Count + 10;
                strSQL = "select * from rmMaterialType";
                DataTable dtPDM = dbPDMcon.GetDataTable(strSQL);
                DataView dvPDM = dtPDM.DefaultView;
                foreach (DataRow drK3 in dtK3.Rows)
                {
                    progressBar1.Value++;
                    dvPDM.RowFilter = "MaterialTypeID='" + drK3["物料类别内码"] + "'";
                    if (dvPDM.Count <= 0)  //Add Items
                    {
                        strSQL = @"Insert Into rmMaterialType (MaterialFItemID,MaterialType,MaterialTypeID)
                                   Values ('{0}','{1}','{2}')";  
                        strSQL = string.Format ( strSQL , drK3["物料类别内码"],drK3["物料类别名称"],drK3["物料类别代码"]);
                    }
                    else
                    {
                        strSQL = "Update rmMaterialType set MaterialType='{0}',MaterialTypeID='{1}' where MaterialFItemID='{2}'";
                        strSQL = string.Format(strSQL, drK3["物料类别名称"], drK3["物料类别代码"], drK3["物料类别内码"]);
                    }
                    dbPDMcon.ExecuteSql(strSQL);
                }
            }
            progressBar1.Visible = false ;
            DBAccess.ConnectionDBString = strOoldCon;
            return true;
        }

        private void frmRMUpdateFromK3Mtn_Load(object sender, EventArgs e)
        {
            FillConnect();
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            UpdateXML();
            if (chkMaterial.Checked || chkUpdateItem.Checked)
            {
                UpdateFromK3();
            }
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Close(); 
        }
    }
}
